<template>
    <div class="words-item">
        <div class="flex items-center justify-between pl-14px pr-8px words-item__title font-bold text-14px">
            <div>
                蒸馏词
            </div>
            <div>
                <el-button type="primary" size="small" @click="handleAdd">添加</el-button>
                <el-button type="success" size="small" @click="handleBatchAdd" class="!ml-8px">批量添加</el-button>
            </div>
        </div>
        <div class="pl-16px pr-16px pt-16px h-350px overflow-hidden words-item__list" v-loading="state.loading">
            <el-scrollbar>
                <el-checkbox-group v-model="selectedKeywords">
                    <el-checkbox :value="keyword.label" v-for="(keyword, index) in keywords"
                        :key="index">
                        <div class="custom-input" :class="{ 'active': keyword.customize }">
                            <div class="flex" v-if="keyword.customize">
                                <el-input :id="'main-input-' + index" v-model="keyword.label"
                                    @input="handleInput(keyword, index)"></el-input>
                                <el-button type="danger" :icon="Delete" @click="handleDelete(keyword, index)"
                                    class="ml-8px"></el-button>
                            </div>
                            <p v-else>{{ keyword.label }}</p>
                        </div>
                    </el-checkbox>
                </el-checkbox-group>
            </el-scrollbar>
        </div>
        <BatchWord v-model:isBatch="state.isBatch" @closeDialog="handleClose" @confirm="handleConfirm"></BatchWord>
    </div>
</template>

<script setup lang="ts">
import { validateStringAllErrors } from '@/utils/index'
import { confirmMessageBox } from '@/utils/elMessageBox'
import { Delete, WarningFilled } from '@element-plus/icons-vue'
import BatchWord from './BatchWord.vue'

const props = defineProps<{
    ruleForm: any;
}>()

const state = reactive({
    activeIndex: -1,
    keyIndex: <number[]>[],
    loading:true,
    isBatch: false
})

const keywords = computed(() => {
    return props.ruleForm.mainWords
})

const selectedKeywords = ref<string[]>([])

// 监听 mainWords 变化，并提取 value > 0 的 label 到 selectedKeywords
watch(
    () => props.ruleForm.mainWords,
    (newMainWords) => {
        state.loading = false
        if(newMainWords.length){
            selectedKeywords.value = newMainWords
            .filter((item: any) => item.value > 0)
            .map((item: any) => item.label);
        }
    },
    { immediate: true }
);

onMounted(() => {
    selectedKeywords.value = props.ruleForm.mainWords
        .filter((item: any) => item.value === 1)
        .map((item: any) => item.label);
})

watch(selectedKeywords, (newVal) => {
    props.ruleForm.mainWords.forEach((item:any) => {
        if (newVal.includes(item.label) && !item.value) {
            item.value = 1
        }else if (!newVal.includes(item.label) && item.value === 1) {
            item.value = 0
        }
    })
}, { deep: true })

function handleInput(value: any, index: number) {
    //检测字符串字符串不能为空、字符串不能包含“医用”、“医疗器械”、“手术器械”、字符串不能超过100字、字符串不能含有特殊字符 
    const result = validateStringAllErrors(value.label)
    if (Array.isArray(result) && result.length > 0) {
        ElMessage.error(result[0])
    }
    if(value.label.length > 0){
        props.ruleForm.mainWords[index].label = value.label
        selectedKeywords.value.push(value.label)
    }
}
function handleDelete(value: any, index: number) {
    confirmMessageBox(WarningFilled, '您确定要删除这条蒸馏词吗？', '', '', () => {
        const labelToRemove = keywords.value[index].label
        // 1. 从 selectedKeywords 移除
        selectedKeywords.value = selectedKeywords.value.filter(item => item !== labelToRemove)
        // 2. 从 mainWords 数组中移除对应对象
        props.ruleForm.mainWords.splice(index, 1)
        let i = state.keyIndex.indexOf(index);
        if (i !== -1) {
            state.keyIndex.splice(i, 1);
        }
    })
}

function handleAdd() {
    const hasEmptyString = props.ruleForm.mainWords.some((obj:any) => Object.values(obj).some(value => value === ''))
    if (hasEmptyString) {
        ElMessage.error('请输入完整的蒸馏词后，才可以继续添加！')
        return
    }else{
        //新增并获取焦点
        props.ruleForm.mainWords.unshift({
            label: '',
            value: 0,
            customize:true
        })

        nextTick(() => {
            const elementId = 'main-input-0'
            const element = document.getElementById(elementId);
            if (element) {
                element.focus();
            }
        })
    }
}

function handleBatchAdd() {
    state.isBatch = true
}

function handleClose() {
    state.isBatch = false
}

function handleConfirm(value:any){
    value.forEach((item: string) => {
        if (item.length > 0) {
            const duplicateIndex = props.ruleForm.mainWords.findIndex((keyword: any) => keyword.label === item)
            if (duplicateIndex !== -1) {
                props.ruleForm.mainWords[duplicateIndex].value = 1
                selectedKeywords.value.unshift(item)
            }else{
                props.ruleForm.mainWords.unshift({
                    label: item,
                    value: 1,
                    customize: true
                })
                selectedKeywords.value.unshift(item)
            }
        }
    })
}

</script>

<style lang="scss" scoped>
:deep(.el-checkbox-group){
    display: block !important;
}
:deep(.el-checkbox__label) {
    width: 90%;
}

:deep(.el-checkbox) {
    margin-right: 0 !important;
    width:33.33%;
}
:deep(.el-input){
    height: 28px;
}
:deep(.el-button--danger){
    height: 28px;
    padding-left: 8px;
    padding-right: 8px;
}
</style>